package com.ms.p2p.plugin.storage;


import com.ms.common.bean.FileInfo;
import com.ms.common.utils.AppContext;
import com.ms.p2p.plugin.AutoRegisterPlugin;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.List;

/**
 * 存储插件接口
 * @author zhenglong
 */
public abstract class StoragePlugin extends AutoRegisterPlugin implements Comparable<StoragePlugin> {

//	@Autowired protected ComponentService componentService;
	
	/**
	 * 是否安装
	 * @return
	 */
	public boolean getIsInstalled() {
		return true;
	}
	
	public final String getId() {
		return ((Component)getClass().getAnnotation(Component.class)).value();
	}
	
	public JSONObject getConfig(){
		/*ComponentDomain component = componentService.getComponent(getId());
		JSONObject obj = (JSONObject)JSONObject.fromObject(component.getConfig()).get("config");
		return obj;*/
		return null;
	}
	
	/**
	 * 是否启用
	 * @return
	 */
	public boolean getIsEnabled() {
		/*ComponentDomain componet = componentService.get("componentId", getId());
		return "1".equals(componet.getEnableState());*/
		return false;
	}

	public Integer getOrder() {
	/*	ComponentDomain componet = componentService.get("componentId", getId());
		return componet.getOrders();*/
		return 1;
	}

	public abstract void upload(String path, File file, String contentType);

	public abstract String getUrl(String path);

	public abstract List<FileInfo> browser(String path);
	
	public String getPath(String file_path){
		return AppContext.getAppRealPath(file_path);
	}
	
	public String getRelativePath(String file_path){
		JSONObject configs = getConfig();
		if(configs != null && configs.get("path") != null){
			String prefix = configs.getString("path");
			return file_path.replace(prefix, "");
		}
		return file_path;
	}

	public void moveLocal(String path, File file){
		upload(path, file, null);
	}

	public void copyLocal(String path, File file){
		upload(path, file, null);
	}
	
	@Override
	public int hashCode() {
		return getId().hashCode();
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		StoragePlugin other = (StoragePlugin) obj;
		return getId().equals(other.getId());
	}


	public int compareTo(StoragePlugin obj) {
		if (this == obj)
			return 0;
		return this.getOrder().compareTo(obj.getOrder());
	}
	
	public String subString(String path){
		JSONObject configs = getConfig();
		if (configs != null) {
			String url = configs.getString("url");
			return getPath(path.replace(url,""));
		} 
		return null;
	}
}
